﻿using System;
using System.IO;
using System.IO.IsolatedStorage;
using SomeKit.Serialization;

namespace SomeKit.Persistence
{
    /// <summary>
    /// Helper class, that uses the SerializationHelper to save objects to files.
    /// </summary>
    public static partial class PersistenceHelper
    {
        /// <summary>
        /// Saves the <paramref name="obj"/> to the file <paramref name="path"/> using the provided <paramref name="objectWriter"/>.
        /// </summary>
        /// <remarks>
        /// If the serializers provided for in SerializationHelper are used, ensure that all types are known (using the KnownType attribute).
        /// </remarks>
        /// <typeparam name="T">A type of object to save.</typeparam>
        /// <param name="obj">The object that should be saved.</param>
        /// <param name="path">The location where the object should be saved to.</param>
        /// <param name="objectWriter">The serializer used for object serialization.</param>
        public static void Save<T>(this T obj, string path, Action<Stream, T> objectWriter)
        {
            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (var file = new IsolatedStorageFileStream(path, FileMode.Create, store))
                {
                    objectWriter(file, obj);
                }
            }
        }

        /// <summary>
        /// Reads an object from the file <paramref name="path"/> using the provided <paramref name="objectReader"/>.
        /// </summary>
        /// <remarks>
        /// If the serializers provided for in SerializationHelper are used, ensure that all types are known (using the KnownType attribute).
        /// </remarks>
        /// <typeparam name="T">A type of object to save.</typeparam>
        /// <param name="path">The location where the object should be read from.</param>
        /// <param name="objectReader"></param>
        /// <returns>The object read from the location <paramref name="path"/>.</returns>
        public static T Load<T>(string path, Func<Stream, T> objectReader)
        {
            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (var file = new IsolatedStorageFileStream(path, FileMode.Open, store))
                {
                    return objectReader(file);
                }
            }
        }
    }
}
